<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\UserOrder;
use app\admin\model\Product;
use app\admin\model\ProductMessage;

class Dingshi extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function _initialize(){
		$this->configuration=M('configuration')->where(array('id'=>1))->find();
	}
	/**
     * 根据经纬度获取当前地区信息
     *
     * @param string $lng 经度
     * @param string $lat 纬度
     * @return Area 城市信息
     */
    public function cityrange(){
        api(array('ret'=>1,'range'=>array(
                array('label'=>'同城','value'=>0),
                array('label'=>'三公里以内','value'=>3),
                array('label'=>'五公里以内','value'=>5),
                array('label'=>'十公里以内','value'=>10),
        )));
    }
    public function getarea()
    {
        $lng=I('longitude');
        $lat=I('latitude');
        $row = M('s_area')->field("id,fid,name,mergename,
        		6371 * acos(
        			cos(radians('".$lat."')) * cos(radians(lat)) * cos(
        				radians(lng) - radians('".$lng."')
        			) + sin(radians('".$lat."')) * sin(radians(lat))
        		
        	) AS distance ")->order("distance asc")->limit(1)->find();
        	
        $area=explode(',',$row['mergename']);
        unset($area[0]);
		api(array('ret'=>1,'area'=>join('-',$area)));	
    }
	public function upload_img(){
	    $upload = new \Think\Upload();// 实例化上传类
    	$upload->maxSize   =     3145728 ;// 设置附件上传大小
    	$upload->exts      =     array('jpg', 'gif', 'png', 'jpeg','docx');// 设置附件上传类型
    	$upload->rootPath  =     './Uploads/'; // 设置附件上传根目录
    	$upload->savePath  =     ''; // 设置附件上传（子）目录
    	// 上传文件 
    	$info   =   $upload->upload();
    	if(!$info) {// 上传错误提示错误信息
       		api(array('ret'=>0,'msg'=>'上传失败'));
	    //	$this->error($upload->getError());
    	}else{// 上传成功
//			print_r($info);
			$url=$this->configuration['site_domain'].'/Uploads/'.$info['file']['savepath'].$info['file']['savename'];
			api(array('ret'=>1,'img_url'=>$url));	
		}
	}
	public function upload_video(){
		require_once 'aliyun-oss-sdk/autoload.php';

		// 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
		$accessKeyId = $this->configuration['accesskeyid'];
		$accessKeySecret = $this->configuration['accesskeysecret'];
		// Endpoint以杭州为例，其它Region请按实际情况填写。
		$endpoint = $this->configuration['endpoint'];
		// 存储空间名称
		$bucket= $this->configuration['bucket'];
		$ext=pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
		$width=I('width',0);
		$height=I('height',0);
		$object = "video/".$width.'_'.$height.'_'.date("YmdHis").rand(1000,9999).'.'.$ext;
		
		// <yourLocalFile>由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt。
		// 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
		$filePath = $_FILES['file']['tmp_name'];
		try{
		    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
		    $ossClient->uploadFile($bucket, $object, $filePath);
			api(array('ret'=>1,'video_url'=>'https://'.$bucket.'.'.$endpoint.'/'.$object,'msg'=>'上传成功'));	
		} catch(OssException $e) {
			api(array('ret'=>0,'video_url'=>'','msg'=>'上传失败'));	
		}
	}
	
	
	public function alioss(){
	    $data=array();
	    $configuration=M('configuration')->where(array('id'=>1))->find();
		$data['accessKeyId']    = $configuration['accesskeyid'];
		$data['accessKeySecret']= $configuration['accesskeysecret'];
		$data['endpoint']       = $configuration['endpoint'];
		$data['bucket']         = $configuration['bucket'];
		$data['SecurityToken']=md5(date("YmdHis").rand(100,999));
		api(array('ret'=>1,'data'=>$data,'msg'=>'ok'));	
        	    
	}
	public function download(){
	    $url=I('url');
		$url=I('url','');
        if(!$url){
            exit('no files');
        }else{
            $filename=substr($url,48,strlen($url)-48);
        }
		$file  =  fopen($url, "rb"); 
		Header( "Content-type:  application/octet-stream "); 
		Header( "Accept-Ranges:  bytes "); 
		Header( "Content-Disposition:  attachment;  filename=".$filename); 
		$contents = "";
		while (!feof($file)) {
			$contents .= fread($file, 8192);
		}
		echo $contents;
		fclose($file); 
        exit();

	    require_once 'aliyun-oss-sdk/autoload.php';
	    $configuration=M('configuration')->where(array('id'=>1))->find();
		$accessKeyId    = $configuration['accesskeyid'];
		$accessKeySecret= $configuration['accesskeysecret'];
		$endpoint       = $configuration['endpoint'];
		$bucket         = $configuration['bucket'];

        // 文件名称。
        $url=I('url','');
        if(!$url){
            exit('no files');
        }else{
            //$url='https://7sz8.oss-cn-hangzhou.aliyuncs.com/files/202209010848544867.mp3';
            $object=substr($url,42,strlen($url)-42);
            echo $object;exit();
            $object = "<yourObjectName>";
        }
        try{
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $content = $ossClient->getObject($bucket, $object);
        } catch(OssException $e) {
            printf(__FUNCTION__ . ": FAILED\n");
            printf($e->getMessage() . "\n");
            return;
        }
        print($content);
	}
	
	public function gmt_iso8601($time){
        return str_replace('+00:00', '.000Z', gmdate('c', $time));
    }
    public function callback(){
        // 1.获取OSS的签名header和公钥url header
        $authorizationBase64 = "";
        $pubKeyUrlBase64 = "";
        /*
         * 注意：如果要使用HTTP_AUTHORIZATION头，你需要先在apache或者nginx中设置rewrite，以apache为例，修改
         * 配置文件/etc/httpd/conf/httpd.conf(以你的apache安装路径为准)，在DirectoryIndex index.php这行下面增加以下两行
            RewriteEngine On
            RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization},last]
         * */
        if (isset($_SERVER['HTTP_AUTHORIZATION'])){
            $authorizationBase64 = $_SERVER['HTTP_AUTHORIZATION'];
        }
        if (isset($_SERVER['HTTP_X_OSS_PUB_KEY_URL']))
        {
            $pubKeyUrlBase64 = $_SERVER['HTTP_X_OSS_PUB_KEY_URL'];
        }

        if ($authorizationBase64 == '' || $pubKeyUrlBase64 == '')
        {
            header("http/1.1 403 Forbidden");
            exit();
        }

        // 2.获取OSS的签名
        $authorization = base64_decode($authorizationBase64);
        // 3.获取公钥
        $pubKeyUrl = base64_decode($pubKeyUrlBase64);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $pubKeyUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $pubKey = curl_exec($ch);
        if ($pubKey == "")
        {
            //header("http/1.1 403 Forbidden");
            exit();
        }

        // 4.获取回调body
        $body = file_get_contents('php://input');

        // 5.拼接待签名字符串
        $authStr = '';
        $path = $_SERVER['REQUEST_URI'];
        $pos = strpos($path, '?');
        if ($pos === false){
            $authStr = urldecode($path)."\n".$body;
        }else{
            $authStr = urldecode(substr($path, 0, $pos)).substr($path, $pos, strlen($path) - $pos)."\n".$body;
        }
        // 6.验证签名
        $ok = openssl_verify($authStr, $authorization, $pubKey, OPENSSL_ALGO_MD5);
        if ($ok == 1){
            header("Content-Type: application/json");
            $data = array("Status"=>"Ok");
            echo json_encode($data);
        }else{
            //header("http/1.1 403 Forbidden");
            exit();
        }
    }
	public function policy(){
	    
	    $configuration=M('configuration')->where(array('id'=>1))->find();
		$id    = $configuration['accesskeyid'];
		$key= $configuration['accesskeysecret'];

        $host = 'https://yuxiangapp.oss-cn-guangzhou.aliyuncs.com';
        $callbackUrl = 'https://app.yuxiang123.cn/api/public/callback';
        $dir = date("Ym").'/';          // 用户上传文件时指定的前缀。

        $callback_param = array(
            'callbackUrl' => $callbackUrl,
            'callbackBody' => 'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}',
            'callbackBodyType' => "application/x-www-form-urlencoded"
        );
        $callback_string = json_encode($callback_param);
        $base64_callback_body = base64_encode($callback_string);
        $now = time();
        $expire = 30;  //设置该policy超时时间是10s. 即这个policy过了这个有效时间，将不能访问。
        $end = $now + $expire;
        $expiration = $this->gmt_iso8601($end);
        //最大文件大小.用户可以自己设置
        $condition = array(0 => 'content-length-range', 1 => 0, 2 => 1048576000);
        $conditions[] = $condition;

        // 表示用户上传的数据，必须是以$dir开始，不然上传会失败，这一步不是必须项，只是为了安全起见，防止用户通过policy上传到别人的目录。
        $start = array(0 => 'starts-with', 1 => '$key', 2 => $dir);
        $conditions[] = $start;

        $arr = array('expiration' => $expiration, 'conditions' => $conditions);
        $policy = json_encode($arr);
        $base64_policy = base64_encode($policy);
        $string_to_sign = $base64_policy;
        $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));

        $response = array();
        $response['accessid'] = $id;
        $response['host'] = $host;
        $response['policy'] = $base64_policy;
        $response['signature'] = $signature;
        $response['expire'] = $end;
        $response['callback'] = $base64_callback_body;
        $response['dir'] = $dir;  // 这个参数是设置用户上传文件时指定的前缀。
        echo json_encode($response);
	}
    /* 
     *阿里云oss二维码重命名
    */
    public function ossrename()
    {


	    require_once 'aliyun-oss-sdk/autoload.php';

	    $configuration=M('configuration')->where(array('id'=>1))->find();
		$accessKeyId    = $configuration['accesskeyid'];
		$accessKeySecret= $configuration['accesskeysecret'];
		$endpoint       = $configuration['endpoint'];
		$bucket         = $configuration['bucket'];

        
        $url=I('url');
        $name=I('name');
        $object = str_replace('https://yuxiangapp.oss-cn-guangzhou.aliyuncs.com/','',$url);//'f/1.jpg';//文件名,需要指定文件夹文件名和后缀

        // 设置URL的有效期为3600秒。
        $timeout = 3600;
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        $new_file_name = $name;//'超级男孩.jpg'; //新的文件名
        $oss_config = array(
            $ossClient::OSS_SUB_RESOURCE => 'response-content-disposition=attachment%3Bfilename%3D'.$new_file_name);
 
        // 生成GetObject的签名URL。
        $signedUrl = $ossClient->signUrl($bucket, $object, $timeout, $ossClient::OSS_HTTP_GET, $oss_config);
        return api([
            'code'=>1,
            'msg'=>'请求成功',
            'data'=>$signedUrl
        ]);
    }

}